package naga

import (
	"bytes"
	"fmt"
	"goPlay/logger"
	"goPlay/picture"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"strconv"
	"time"
)

func GetGuolao(url string) {
	err := os.MkdirAll("./small_pic/"+url, os.ModePerm) //在当前目录下生成md目录
	if err != nil {
		fmt.Println(err)
	}
	path := "./small_pic/" + url + "/"

	pic := picture.GetImg(url)

	// get img data
	// so
	// posdata := img.GetImgLine(img_data, format)
	posdata := pic.GetPicLine()
	// cut img data
	imgs := pic.CutPic(posdata, path)

	// img_data, format := picture.GetImg("http://7xohdn.com2.z0.glb.qiniucdn.com/1.png")
	// posdata := img.GetImgLine(img_data)
	// cut img data
	f, err1 := os.Create(path + "guolao.txt")
	fmt.Println("write err", err1)
	defer f.Close()
	_, err1 = io.WriteString(f, fmt.Sprintf("%d", posdata))
	fmt.Println("write err2", err1)

	for k, img := range imgs {
		bodyBuf := &bytes.Buffer{}
		bodyWriter := multipart.NewWriter(bodyBuf)
		buf, err := img.Encode()
		if err != nil {
			logger.Error("Encode img err", err)
			return
		}
		fileWriter, err := bodyWriter.CreateFormFile("pic", "pic")
		if err != nil {
			logger.Error("error writing to buffer", err)
			return
		}

		_, err = io.Copy(fileWriter, buf)
		if err != nil {
			logger.Error("io copy error:", err)
			return
		}

		contentType := bodyWriter.FormDataContentType()
		bodyWriter.Close()

		c := &http.Client{
			Timeout: 300 * time.Second,
		}

		resp, err := c.Post("http://www.ngrok.wordstore.knowbox.cn:9158/math", contentType, bodyBuf)
		if err != nil {
			logger.Error("http post error:", err)
			return
		}
		defer resp.Body.Close()
		resp_body, err := ioutil.ReadAll(resp.Body)
		jsonstr := bytes.NewBuffer(resp_body).String()
		img_f, err1 := os.Create(path + strconv.Itoa(k) + "minwei.txt")
		defer img_f.Close()
		_, err1 = io.WriteString(img_f, jsonstr)
		fmt.Println("end", err1, jsonstr)
	}

}
